import {
  createRouter,
  createWebHistory,
  type RouteLocationNormalized
} from "vue-router";
import routes from "./routes";
import { useCachedViewStoreHook } from "@/store/modules/cached-view";
import NProgress from "@/utils/progress";
import setPageTitle from "@/utils/set-page-title";
import { useUserStore } from "@/store/useUserStore";
import { isSameDomain } from "@/utils/url";
import { useAuthStore } from "@/store/useAuthStore";
import { useLocationParams } from "@/store/useLocationStore";

const router = createRouter({
  history: createWebHistory(import.meta.env.VITE_PUBLIC_PATH),
  routes
});

export interface toRouteType extends RouteLocationNormalized {
  meta: {
    noAuth: any;
    title?: string;
    noCache?: boolean;
  };
}
router.beforeEach((to: toRouteType, from, next) => {
  NProgress.start();
  // 路由缓存
  // useCachedViewStoreHook().addCachedView(to);
  // 页面 title
  setPageTitle(to.meta.title);
  // const userStore = useUserStore();
  if (to.meta.noAuth) {
    // 如果是经销商域名且需要登陆
    // if (to.path == "/login" && !isSameDomain()) {
    //   const { handleAuth } = useAuthStore();
    //   handleAuth(from);
    // }
    next();
  } else {
    // if (!userStore.isAuthenticated()) {
    //   next({ path: "/login", query: to.query });
    // } else {
    next();
    // }
  }
  return true;
});

router.afterEach(to => {
  NProgress.done();
  if (!to.meta.noAuth) {
    const { getParam, removeParam, updateParam } = useLocationParams();
    updateParam();
    const toRemoveList = ["code"];
    toRemoveList.forEach(item => {
      if (getParam(item)) {
        removeParam(item);
      }
    });
  }
});

export default router;
